<template>
  <a-drawer
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%"
  >
    <template slot="title">
      <div style="width: 100%">
        <span>新建报告</span>
      </div>
    </template>

    <a-spin :spinning="confirmLoading" style="padding-bottom: 20px">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item
          label="报告名称"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          prop="reportName"
        >
          <a-input placeholder="请输入报告名称" v-model="model.reportName" />
        </a-form-model-item>
        <!-- 模板类别 -->
        <!-- 所属行业 -->
        <a-form-model-item
          label="报告模板"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
           prop="reportType"
     
        >
          <a-radio-group v-model="model.reportType" :defaultValue="1">
            <a-radio :value="1"> 发改委模板 </a-radio>
            <a-radio :value="0" disabled> GHG </a-radio>
          </a-radio-group>
        </a-form-model-item>

        <!-- 所属行业 -->
        <a-form-model-item
          label=" "
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          prop="industryId"
        >
          <a-select
            @change="handleSelectChange"
            placeholder="请选择行业"
            v-model="model.industryId"
          >
            <a-select-option
              v-for="(item, index) in industryList"
              :key="index"
              :value="item.id"
            >
              {{ item.industryName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!--选择任务-->
        <a-form-model-item
          label="填报任务"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          prop="taskIds"
        >
          <a-transfer
            :data-source="mockData"
            show-search
            :list-style="{ width: '400px', height: '300px' }"
            :titles="['填报任务', '已选任务']"
            :operations="['选择', '取消']"
            :target-keys="model.taskIds"
            :render="(item) => `${item.taskName}`"
            @change="handleChange"
          >
            <span slot="notFoundContent">没数据</span>
          </a-transfer>
          <a-input
            style="
              position: absolute;
              left: 0;
              width: 0;
              height: 0;
              padding: 0;
              border: none;
            "
            v-model="model.taskIds"
          />
        </a-form-model-item>
        <!-- 描述 -->
        <a-form-model-item
          label="描述"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          prop="description"
        >
          <a-textarea
            :rows="5"
            v-model="model.description"
            placeholder="请输入报告描述信息"
          />
        </a-form-model-item>
      </a-form-model>
    </a-spin>

    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-popconfirm
        title="确定放弃编辑？"
        @confirm="handleCancel"
        okText="确定"
        cancelText="取消"
      >
        <a-button style="margin-right: 4px">取消</a-button>
      </a-popconfirm>
      <a-button
        @click="handleSubmit"
        type="primary"
        class="confirm"
        :loading="confirmLoading"
        >生成报告</a-button
      >
    </div>
  </a-drawer>
</template>

<script>
//   import moment from 'moment'
import Vue from "vue";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { getAction } from "@/api/manage";
import {
  addUser,
  addReoprt,
  editUser,
  queryUserRole,
  queryall,
  queryFinishedTaskList,
  getAccountingIndustry,
} from "@/api/api";
import { disabledAuthFilter } from "@/utils/authFilter";

export default {
  name: "ReportModal",
  components: {},
  data() {
    return {
      mockData: [],
      targetKeys: [],
      departDisabled: false, //是否是我的部门调用该页面
      roleDisabled: false, //是否是角色维护调用该页面      drawerWidth: 700,
      modaltoggleFlag: true,
      confirmDirty: false,
      userId: "", //保存用户id
      disableSubmit: false,
      dateFormat: "YYYY-MM-DD",
      validatorRules: {
        reportType: [{ required: true, message: "请输入报告模板!" }],
        reportName: [{ required: true, message: "请输入报告名称!" }],
        industryId: [{ required: true, message: "请选择行业!" }],
        taskIds: [{ required: true, message: "请选择任务!" }],
        password: [
          {
            required: true,
            pattern:
              /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
            message: "密码由8位数字、大小写字母和特殊符号组成!",
          },
          { validator: this.validateToNextPassword, trigger: "change" },
        ],
        confirmpassword: [
          { required: true, message: "请重新输入登录密码!" },
          { validator: this.compareToFirstPassword },
        ],
        realname: [{ required: true, message: "请输入用户名称!" }],
        phone: [
          { required: true, message: "请输入手机号!" },
          { validator: this.validatePhone },
        ],
        email: [{ validator: this.validateEmail }],
        roles: {},
        workNo: [
          { required: true, message: "请输入工号" },
          { validator: this.validateWorkNo },
        ],
        telephone: [
          {
            pattern: /^0\d{2,3}-[1-9]\d{6,7}$/,
            message: "请输入正确的座机号码",
          },
        ],
      },
      departIdShow: false,
      title: "新建用户",
      visible: false,
      model: { reportType: 1 },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      uploadLoading: false,
      confirmLoading: false,
      headers: {},
      url: {
        fileUpload: "",
        //   fileUpload: window._CONFIG['domianURL']+"/sys/common/upload",
        userWithDepart: "/sys/user/userDepartList", // 引入为指定用户查看部门信息需要的url
        userId: "/sys/user/generateUserId", // 引入生成添加用户情况下的url
        syncUserByUserName: "/act/process/extActProcess/doSyncUserByUserName", //同步用户到工作流
        queryTenantList: "/sys/tenant/queryList",
      },
      tenantsOptions: [],
      rolesOptions: [],
      nextDepartOptions: [],
      industryList: [],
    };
  },
  created() {
    this.getAccountingIndustryFun();
  },
  computed: {
    uploadAction: function () {
      return this.url.fileUpload;
    },
  },
  methods: {
    // 切换行业
    handleSelectChange(val) {
      queryFinishedTaskList({ industryId: val,reportType:this.model.reportType }).then((res) => {
        if (res.code == 200) {
          this.mockData = this.initData(res.result);
        } else {
          this.mockData = [];
        }
      });
    },
    // 获取行业数据
    getAccountingIndustryFun() {
      getAccountingIndustry().then((res) => {
        this.industryList = res.result;
      });
    },
    // 初始化数据
    initData(data) {
      const mockData = [];
      const targetKeys = [];
      var len = data.length;
      for (let i = 0; i < len; i++) {
        const dataObj = {
          key: `${data[i].id}`,
          title: `${data[i].id}`,
          description: `${data[i].description}`,
          taskName: `${data[i].taskName}`,
        };
        mockData.push(dataObj);
      }
      return mockData;
    },
    validatorTask(rule, value, callback) {
      if (value.length > 0) {
        callback();
      } else {
        callback("请选择任务");
      }
    },
    handleChange(targetKeys, direction, moveKeys) {
      //   console.log(targetKeys, direction, moveKeys);
      Vue.set(this.model, "taskIds", targetKeys);
    },
    add() {
      this.edit({ activitiSync: "1", userIdentity: 1 });
    },

    edit(record) {
      let that = this;
      that.visible = true;
      // this.model = Object.assign({}, record);
      //根据屏幕宽度自适应抽屉宽度
      this.resetScreenSize();

      //   console.log(record)
    },

    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth;
      } else {
        this.drawerWidth = 1200;
      }
    },

    close() {
      this.$emit("close");
      this.visible = false;
      this.disableSubmit = false;
      this.nextDepartOptions = [];
      this.departIdShow = false;
      this.$refs.form.resetFields();
    },

    handleSubmit() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        //   console.log(valid);
        if (valid) {
          that.confirmLoading = true;
          let obj;
          let param = {
            ...this.model,
          };
          param.taskIds = param.taskIds.join(",");
          obj = addReoprt(param);
          obj
            .then((res) => {
              if (res.success) {
                //   console.log(res);
                that.$message.success(res.message);
                that.$emit("ok");
              } else {
                that.$message.warning(res.message);
              }
            })
            .finally(() => {
              that.confirmLoading = false;
              that.close();
            });
        } else {
          return false;
        }
      });
    },
    handleCancel() {
      this.close();
    },
  },
};
</script>

<style   lang="scss">
@import "@/assets/css/newrModule.scss";
</style>
